import Vue from "vue";
import VueRouter from "vue-router";
import Login from '@/components/Login'
import Welcome from '@/components/Welcome'
import Users from '@/components/user/Users'
import Reports from '@/components/report/Reports'
import Rights from '@/components/power/Rights'
import Roles from '@/components/power/Roles'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Login
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/home',
    // 重定向
    redirect: '/welcome',
    name: 'Home',
    component: () => import('@/views/Home'),
    children: [
      {
        path: '/welcome',
        name: 'Welcome',
        component: Welcome
      },
      {
        path: '/users',
        name: 'Users',
        component: Users
      },
      {
        path: '/rights',
        name: 'Rights',
        component: Rights
      },
      {
        path: '/roles',
        name: 'Roles',
        component: Roles
      },
      {
        path: '/reports',
        name: 'Reports',
        component: Reports
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

//挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // 获取token值
  const token = window.sessionStorage.getItem('token');
  //to 代表将要访问的路径
  //from 从哪个路径跳转而来
  //next() 放行 next('./login') 强制跳转
  if (to.path !== '/login') {
    if (!token) {
      next('/login')
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router